/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.task;

import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.model.Page;
import com.apache.database.model.TaskEntity;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import org.apache.commons.io.IOUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import java.io.*;
import java.util.*;

/**
 * description:  配置文件读取工具类
 *
 * @author Hou Dayu 创建时间：2016-1-14
 */
public class XmlReader {

    private String filePath;

    private static XmlReader instance;

    private String fileName = "taskconfig.xml";

    private XmlReader() {
        filePath = ConfigUtil.getClassLoaderPath() + "config/";
    }

    public synchronized static XmlReader newInstance() {
        if (null == instance) {
            instance = new XmlReader();
        }
        return (instance);
    }

    public List<TaskEntity> readerConfig() {
        try {
            return validate();
        } catch (Exception e) {
            try {
                return validateJar();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return new ArrayList<TaskEntity>();
    }

    public List<TaskEntity> readerDatabase(String sysName) {
        Map map = new HashMap();
        map.put("sysName", sysName);
        map.put("method", "list");
        InterfaceRegister register = PortalPubFactory.getInstance().getRpcInfo("rpc");
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient("rpcService", "taskTimerAction", map, register);
        if (null != entity.getEntity()) {
            if (entity.getEntity() instanceof Page) {
                return ((Page) entity.getEntity()).getPageObjects();
            } else {
                return (List) entity.getEntity();
            }
        }
        return new ArrayList<TaskEntity>();
    }

    private List<TaskEntity> validate() throws Exception {
        InputStream in = new FileInputStream(filePath + fileName);
        SAXBuilder sx = new SAXBuilder();
        Document doc = sx.build(in);
        return initTaskEntitys(doc);
    }

    private List<TaskEntity> validateJar() throws Exception {
        InputStream in = this.getClass().getResourceAsStream("/config/" + fileName);
        SAXBuilder sx = new SAXBuilder();
        Document doc = sx.build(in);
        return initTaskEntitys(doc);
    }

    /**
     * description: 初始化license信息
     */
    private List<TaskEntity> initTaskEntitys(Document doc) throws Exception {
        List<TaskEntity> result = new ArrayList<TaskEntity>();

        Element rootelement = doc.getRootElement();
        List<Element> childs = rootelement.getChildren();
        for (int i = 0; i < childs.size(); i++) {
            TaskEntity tModel = new TaskEntity();
            tModel.setTaskKey("task-" + getRandomStr("", 9));
            tModel.setClassName(childs.get(i).getChildText("class"));
            //			tModel.setMethodName(childs.get(i).getChildText("methodName"));
            //			tModel.setTaskType(childs.get(i).getChildText("taskType"));
            String intervalType = StrUtil.doNull(childs.get(i).getChildText("intervalType"), "0");
            tModel.setIntervalType(Long.valueOf(intervalType));
            tModel.setHour(Long.valueOf(childs.get(i).getChildText("hour")));
            tModel.setMinute(Long.valueOf(childs.get(i).getChildText("minute")));
            tModel.setSecond(Long.valueOf(childs.get(i).getChildText("second")));
            if (StrUtil.isNotNull(childs.get(i).getChildText("startTime"))) {
                tModel.setStartTime(Integer.valueOf(childs.get(i).getChildText("startTime")));
            }
            if (StrUtil.isNotNull(childs.get(i).getChildText("endTime"))) {
                tModel.setEndTime(Integer.valueOf(childs.get(i).getChildText("endTime")));
            }
            if (StrUtil.isNotNull(childs.get(i).getChildText("taskStatus"))) {
                tModel.setTaskStatus(Integer.valueOf(childs.get(i).getChildText("taskStatus")));
            }
            tModel.setDescription(childs.get(i).getChildText("description"));
            result.add(tModel);
        }
        return result;
    }

    /**
     * description:  写任务配置
     *
     * @param tasks
     * @return
     */
    public boolean writeXml(List<TaskEntity> tasks) {
        boolean mark = false;
        StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("  <taskconfig>\n");
        if (!StrUtil.isEmpty(tasks)) {
            for (TaskEntity task : tasks) {
                sb.append("    <task>\n");
                sb.append("       <class>" + task.getClassName() + "</class>\n");
                //				sb.append("       <methodName>" + task.getMethodName() + "</methodName>\n");
                //				sb.append("       <taskType>" + task.getTaskType() + "</taskType>\n");
                sb.append("       <intervalType>" + task.getIntervalType() + "</intervalType>\n");
                sb.append("       <hour>" + task.getHour() + "</hour>\n");
                sb.append("       <minute>" + task.getMinute() + "</minute>\n");
                sb.append("       <second>" + task.getSecond() + "</second>\n");
                sb.append("       <startTime>" + task.getStartTime() + "</startTime>\n");
                sb.append("       <endTime>" + task.getEndTime() + "</endTime>\n");
                sb.append("       <description>" + task.getDescription() + "</description>\n");
                sb.append("       <taskStatus>" + task.getTaskStatus() + "</taskStatus>\n");
                sb.append("    </task>\n");
            }
        }
        sb.append("  </taskconfig>");
        mark = newCreateFile(filePath, sb.toString());
        return mark;
    }

    public String noZero(String key, int leng, String align) {
        String gest = "";
        String value = "";
        for (int i = 0; i < leng; i++) {
            gest += "0";
        }
        if ("l".equals(align)) {
            value = gest + key;
        } else {
            value += key + gest;
        }
        return value;
    }

    /**
     * 按类型与长度生成随机数
     *
     * @param type word为纯字母，number为纯数字，其他为字母与数字
     * @param maxNum 随机数的长度
     * @return
     */
    public String getRandomStr(String type, int maxNum) {
        String numStr = "";
        int count = 36;
        if ("word".equalsIgnoreCase(type)) {
            numStr = "abcdefghigkmnopqrstuvwsyzl";
            count = 26;
        } else if ("number".equalsIgnoreCase(type)) {
            numStr = "0123456789";
            count = 10;
        } else {
            numStr += "ab0cde2fgh8ig6klm9no3pqr7stu4vws5yz1";
        }
        String str = "";
        int intRd = 0; //存放随机数
        boolean[] bool = new boolean[count];
        Random rdm = new Random();
        for (int i = 0; i < maxNum; i++) {//随机排序
            do {
                intRd = rdm.nextInt(count); //假如产生的数相同继续循环
            } while (bool[intRd]);
            bool[intRd] = true;
            str += numStr.charAt(intRd);
        }
        return str;
    }

    /**
     * 创建新的文件
     *
     * @param filePathAndName 文件名称
     * @param fileContent 文件内容
     */
    private boolean newCreateFile(String filePathAndName, String fileContent) {
        boolean result = true;
        newCreateFolder(filePathAndName);
        FileOutputStream fo = null;
        OutputStreamWriter osw = null;
        PrintWriter out1 = null;
        try {
            fo = new FileOutputStream(filePathAndName + fileName);//"content_page.js");
            osw = new OutputStreamWriter(fo, "UTF-8");
            out1 = new PrintWriter(osw);
            out1.println(fileContent);
            out1.close();
            osw.close();
            fo.close();
        } catch (Exception e) {
            return false;
        } finally {
            IOUtils.closeQuietly(out1);
            IOUtils.closeQuietly(osw);
            IOUtils.closeQuietly(fo);
        }
        return result;
    }

    /**
     * 新建目录操作
     *
     * @param folderPath 文件夹路径
     */
    private boolean newCreateFolder(String folderPath) {
        boolean result = false;
        try {
            if (StrUtil.isNotNull(folderPath)) {
                File newFilePath = new File(folderPath);
                if (!newFilePath.exists()) {
                    result = newFilePath.mkdirs();
                }
                File newFile = new File(folderPath + fileName);
                if (!newFile.exists()) {
                    return newFile.createNewFile();
                }
            }
        } catch (Exception e) {
            return false;
        }
        return result;
    }
}
